package com.setup.trac.aop.logging;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.MethodBeforeAdvice;

public class LoggingInterceptor {

	private static Logger log = Logger.getLogger("tracsetup");

	public LoggingInterceptor() {
		try {
			Properties properties = new Properties();
			properties
					.load(LoggingInterceptor.class
							.getResourceAsStream("/com/setup/trac/etc/log4j.properties"));
			PropertyConfigurator.configure(properties);
			log.info("LoggingIntereceptor intialized...");
		} catch (IOException e) {
			System.out.println("Logger non inizializzato: " + e.getMessage()
					+ ", " + e);
		}
	}


	public void logAfter(JoinPoint joinPoint) throws Throwable {
		String methodName = joinPoint.getSignature().toLongString();
		Object[] args = joinPoint.getArgs();
		Object target = joinPoint.getTarget();
		log.info("[AFTER] "+methodName);
	}
	
	public void logAfterReturning(Object result){
		log.info("[RETURN] "+result);

	}
	
	public void logBefore(JoinPoint joinPoint) throws Throwable {
		String methodName = joinPoint.getSignature().toLongString();
		Object[] args = joinPoint.getArgs();
		Object target = joinPoint.getTarget();
		log.info("[BEFORE] "+methodName);
		if(args!=null && args.length>0){
			log.debug("Parametri in input ");
			for (int i = 0; i < args.length; i++) {
				StringBuffer sb = new StringBuffer();
				Object object = args[i];
				log.debug(sb.append("Param[").append(i).append("]:").append(object).toString());
			}
		}
		
	}



}
